package com.tanhua.server.service;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.commons.templates.OssTemplate;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.FollowUser;
import com.tanhua.domain.mongo.Publish;
import com.tanhua.domain.mongo.Video;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.domain.vo.VideoVo;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.mongo.VideoApi;
import com.tanhua.server.Interceptor.UserHolder;
import org.apache.dubbo.config.annotation.Reference;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class VideoService {

    @Reference
    private VideoApi videoApi;


    @Reference
    private UserInfoApi userInfoApi;

    @Autowired
    private OssTemplate ossTemplate;


    @Autowired
    private FastFileStorageClient storageClient;


    @Autowired
    private FdfsWebServer webServer;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private VideoMqService videoMqService;


    //视频列表
//    @Cacheable(value = "videoList",key = "#page+'_'+#pagesize") // 1,10   2 10
    public PageResult queryVideoList(Integer page, Integer pagesize) {
        System.out.println("============从数据库中查询了视频==================");
        //1. 查询缓存得到大数据团队推送的视频
        PageResult pageResult =this.findRecommend(page, pagesize, UserHolder.getUserId());
        if(pageResult==null) {
            pageResult =  videoApi.findByPage(page, pagesize);
        }
        //2. 得到视频列表List<Video>
        List<Video> videoList = (List<Video>) pageResult.getItems();
        List<VideoVo> videoVoList = new ArrayList<>();
        //3. 遍历视频列表，把Video的数据转换为VideoVo，添加到集合
        if(videoList!=null) {
            for (Video video : videoList) {
                VideoVo videoVo = new VideoVo();
                //查询视频上传人的用户信息
                UserInfo userInfo = userInfoApi.findById(video.getUserId());
                if(userInfo!=null) {
                    BeanUtils.copyProperties(userInfo, videoVo);
                }
                BeanUtils.copyProperties(video,videoVo);
                videoVo.setId(video.getId().toString());
                videoVo.setCover(video.getPicUrl()); //视频的封面图片
                videoVo.setSignature(video.getText()); //视频的签名，标题
                videoVo.setHasLiked(0);
                String key ="followUser_"+UserHolder.getUserId()+"_"+video.getUserId();
                if(redisTemplate.hasKey(key)){
                    videoVo.setHasFocus(1);
                }else {
                    videoVo.setHasFocus(0);
                }
                videoVoList.add(videoVo);
            }
        }
        //4. 修改pageResult存储的数据
        pageResult.setItems(videoVoList);

        //目标： 存储VideoVo对象
        return pageResult;
    }

    private PageResult findRecommend(Integer page, Integer pagesize, long userId) {
        //1. 从redis中取出推荐的朋友圈的pid
        String value = redisTemplate.opsForValue().get("QUANZI_VIDEO_RECOMMEND_" + userId);

        //2. 如果取出为null，直接返回null。
        if(value==null){
            return null;
        }
        //1,2,3,45,6,7,8,9,10
        String[] vids = value.split(",");

        //3. 计算开始索引值与结束的索引值，   1,2,3,4，5,6,7,8,9,10      1 每页3条
        int  startIndex = (page-1)*pagesize;//开始索引值
        List<Long> vidList = new ArrayList<>();
        if(startIndex<vids.length){
            //计算结束索引值
            int endIndex = startIndex+pagesize-1;//0+3-1=2
            if(endIndex>=vids.length){
                endIndex = vids.length-1;
            }
            //根据startIndex与endIndex 取出pid出来
            for (int i = startIndex; i <=endIndex ; i++) {
                String pid = vids[i];
                //把pid添加到一个集合中
                vidList.add(Long.valueOf(pid));
            }
        }
        //根据pid查找动态
        List<Video> publishList = videoApi.findByVid(vidList);
        //4. 根据索引值查找对应的朋友圈，构建一个Pageresult对象返回
        return new PageResult(page,pagesize,vids.length,publishList);
    }

    //视频上传
    @CacheEvict(value = "videoList",allEntries = true) //上传视频马上清除缓存
    public ResponseEntity uploadVideos(MultipartFile videoThumbnail, MultipartFile videoFile, String text) throws IOException {

        //1. 上传封面图片到阿里云
        String picUrl = ossTemplate.upload(videoThumbnail.getOriginalFilename(), videoThumbnail.getInputStream());

        //2. 上传视频文件到fastdfs  abc.mp3
        String videoFileName = videoFile.getOriginalFilename();
        String extName = videoFileName.substring(videoFileName.lastIndexOf(".")+1);
        StorePath storePath = storageClient.uploadFile(videoFile.getInputStream(), videoFile.getSize(), extName, null);
        String videoUrl = webServer.getWebServerUrl()+storePath.getFullPath();

        //3. 创建Video，补全参数
        Video video = new Video();
        video.setUserId(UserHolder.getUserId()); //视频上传人的id
        if(text!=null) {
            video.setText(text); //视频的标题
        }else{
            video.setText("左手右手一个慢动作~");
        }
        video.setPicUrl(picUrl);
        video.setVideoUrl(videoUrl);
        video.setCreated(System.currentTimeMillis());
        video.setLikeCount(0);
        video.setCommentCount(0);
        video.setLoveCount(0);
        video.setId(ObjectId.get());
        //4. 保存Video
        videoApi.save(video);
        videoMqService.videoMsg(video.getId().toString()); //发送消息到mq 中

        return ResponseEntity.ok(null);
    }

    //关注视频的作者
    public ResponseEntity followUser(long followUserId) {

        //1 .创建FollowerUser
        FollowUser followUser = new FollowUser();
        followUser.setCreated(System.currentTimeMillis());
        followUser.setUserId(UserHolder.getUserId());
        followUser.setFollowUserId(followUserId);
        videoApi.followUser(followUser);
        //2. 添加一个一关注标记在redis中
        String key ="followUser_"+UserHolder.getUserId()+"_"+followUserId;
        redisTemplate.opsForValue().set(key,"1");

        return ResponseEntity.ok(null);

    }

    //取消关注用户
    public ResponseEntity unfollowUser(long followUserId) {
        //1. 创建FollowerUser,删除
        FollowUser followUser = new FollowUser();
        followUser.setUserId(UserHolder.getUserId());
        followUser.setFollowUserId(followUserId);
        videoApi.unfollowUser(followUser);
        //2. 删除redis标记
        String key ="followUser_"+UserHolder.getUserId()+"_"+followUserId;
        redisTemplate.delete(key);
        return ResponseEntity.ok(null);

    }
}
